package com.aaa.screenrecorder;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private static final int request_code_permission = 110;
    private static final int request_code_media_projection = 120;

    private String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
    };

    private MediaProjectionManager mMediaProjectionManager;

    private TextView mTvTime;
    private View mBtnScreenRecorder;
    private ScreenRecorderService.ScreenRecorderBinder mRecorderBinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissions, request_code_permission);
        }

        initView();
    }

    // 初始化点击事件
    private void initView() {
        View.OnClickListener clickListener = (view) -> {
            switch (view.getId()) {
                case R.id.btn_record_screen:
                    startRecord();
                    break;
                case R.id.btn_capture_screen:
                    stopRecord();
                    break;
            }
        };

        mBtnScreenRecorder = findViewById(R.id.btn_record_screen);
        mBtnScreenRecorder.setOnClickListener(clickListener);

        findViewById(R.id.btn_capture_screen).setOnClickListener(clickListener);

        // 子线程时间计数器
        mTvTime = findViewById(R.id.tv_time);
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(() -> {
                    mTvTime.setText(Utils.getDateString());
                });
            }
        }).start();
    }

    private void stopRecord() {
        mBtnScreenRecorder.setBackgroundColor(Color.WHITE);
        if (mRecorderBinder != null) {
            mRecorderBinder.stopRecord();
        }
    }

    private void startRecord() {
        // 申请通过就保存在内存里，避免每次都申请
        if (Utils.data != null) {
            startScreenRecordService(Utils.data);
            return;
        }

        mMediaProjectionManager = (MediaProjectionManager) getApplicationContext().getSystemService(MEDIA_PROJECTION_SERVICE);
        startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), request_code_media_projection);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == request_code_media_projection) {
            if (resultCode == RESULT_OK) {
                startScreenRecordService(data);
            }
        }
    }

    private void startScreenRecordService(Intent data) {
        // 申请通过就保存在内存里，避免每次都申请，Intent只能内存序列化，不能持久化 todo
        Utils.data = data;

        Intent intent = new Intent(MainActivity.this, ScreenRecorderService.class);
        intent.putExtra("data", data);

        bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d(TAG, "onServiceConnected: ");
                mRecorderBinder = (ScreenRecorderService.ScreenRecorderBinder) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.d(TAG, "onServiceDisconnected: ");
                mRecorderBinder = null;
            }
        }, Context.BIND_AUTO_CREATE);

        // 不仅bindService，还要startService，避免Activity退出引起Service退出
        // 适配 8.0+ 的前台服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }

        mBtnScreenRecorder.setBackgroundColor(Color.GREEN);
    }

}
